import { Injectable } from '@nestjs/common';
import { CreateTongBuPositionDto } from './dto/create-tong-bu-position.dto';
import { UpdateTongBuPositionDto } from './dto/update-tong-bu-position.dto';
import { formatError, formatPage, formatSearchTime, formatSuccess } from 'src/util';
import { InjectRepository } from '@nestjs/typeorm';
import { TongBuPosition } from './entities/tong-bu-position.entity';
import { Between, Repository } from 'typeorm';

@Injectable()
export class TongBuPositionService {
  constructor(
    @InjectRepository(TongBuPosition)
    private readonly tongBuPositionRepository: Repository<TongBuPosition>,
  ) {}

  // 定时同步芝麻的历史仓位
  // async tongBuHistoryPositions() {
  //   const list = [{}];
  //   // const res = await this.searchAllUserLsPositions({});
  //   return formatSuccess({
  //     a: 1,
  //   });
  // }

  // 查询
  async findAll({ current = 1, pageSize = 10000000, startTime = null, endTime = null, yuanGongId = null }) {
    const pageNum = current || 1;
    // 查询条件
    const where: any = {};
    if (startTime && endTime) where.tongBuTime = Between(startTime + ' 00:00:00', endTime + ' 24:00:00');
    if (yuanGongId) where.userId = yuanGongId;
    // 获取总条数
    const total = await this.tongBuPositionRepository.count({ where });
    // 查第几页的数据
    let list = [];
    if (total > 0) {
      list = await this.tongBuPositionRepository.find({
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
        where,
        order: { create_time: 'DESC' },
      });
    }
    return formatPage({ pageNum, pageSize, total, list });
  }

  // 删除所有记录信息
  async deleteAll(list: any = null) {
    let datas = list;
    if (!list) datas = (await this.findAll({}))?.data?.list;
    const ids = datas.map(({ id }) => +id);
    await this.tongBuPositionRepository.delete(ids);
    return formatSuccess(true);
  }

  // 修改
  async edit(params) {
    const data = await this.tongBuPositionRepository.update({ id: params.id }, params);
    if (data.affected > 0) {
      return formatSuccess('成功');
    } else {
      return formatError({ msg: '失败' });
    }
  }

  // 批量修改同步时间
  async editTongbuTime() {
    const params = {
      id: 1623,
      tongBuTime: '2025-03-22 24:00:00',
    };
    this.edit(params);
    // const list = (await this.findAll({}))?.data?.list;
    // const arr = list.map((item) => {
    //   const params = {
    //     id: item.id,
    //     tongBuTime: item?.tongBuTime + ' 24:00:00',
    //   }
    //   return this.edit(params);
    // })
    // const res: any = await Promise.allSettled(arr);
    return formatSuccess('成功');
  }

  // 删除误添加的记录信息
  async deleteErrorData() {
    const list = (await this.findAll({}))?.data?.list.filter((item) => item.tongBuTime.includes('18:00:00'));
    const arr = list.map((item) => this.tongBuPositionRepository.delete({ id: item.id }));
    Promise.allSettled(arr);
    return formatSuccess('删除成功');
  }
}
